import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { ConfigService, ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { LinkModule } from './modules/link/link.module';
import { UserModule } from './modules/user/user.module';
import { AuthModule } from './modules/auth/auth.module';
import { TagModule } from './modules/tag/tag.module';
import { CategoryModule } from './modules/category/category.module';
import { APP_GUARD, MiddlewareBuilder } from '@nestjs/core';
import JwtAuthGuard from './guard/jwt-auth.grard';
import config from '~/config'
import { LoggerMiddleware } from './middleware';
@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      expandVariables: true,
      // 指定多个 env 文件时，第一个优先级最高
      envFilePath: ['.env.local', `.env.${process.env.NODE_ENV}`, '.env'],
      load: [...Object.values(config)],
    }),
    // 异步配置
    TypeOrmModule.forRootAsync({
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        type: 'mysql',
        host: configService.get('DB_HOST'),
        port: configService.get('DB_PORT'),
        username: configService.get('DB_USER'),
        password: configService.get('DB_PASSWORD'),
        database: configService.get('DB_DATABASE'),
        // entities: [__dirname + '/**/*.entity{.ts,.js}'],
        // 自动载入实体
        autoLoadEntities: true,
        // 默认：false，如果为true，自动载入的模型将同步，禁止生产环境使用，否则数据将会丢失
        synchronize: true,
        // 打印原始sql
        // logging: true,
        logging: ['query', 'error'],
      }),
    }),
    LinkModule,
    UserModule,
    AuthModule,
    TagModule,
    CategoryModule,
  ],
  controllers: [AppController],
  providers: [AppService, {
    provide: APP_GUARD,
    useClass: JwtAuthGuard
  }],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    // 监听 login 访问，注册 logger 中间件
    consumer.apply(LoggerMiddleware).forRoutes('*')
    // 其他的注册方式都支持...
  }
}
